//
//  HGProfileVC.m
//  RedWinMall
//
//  Created by HeDianZhao on 2018/8/3.
//  Copyright © 2018年 HeDianZhao. All rights reserved.
//

#import "HGProfileVC.h"
#import "OSSService.h"
#import "NSString+Extension.h"
#import "QQNavigationController.h"
#import "QQForgetPassWViewController.h"
#import "XZCustomCamer.h"
#import "QQLoginViewController.h"

@interface HGProfileVC ()

@property (weak, nonatomic) IBOutlet UIButton *headImage;
@property (weak, nonatomic) IBOutlet UILabel *phoneNum;
@property (weak, nonatomic) IBOutlet UIView *editView;
@property (weak, nonatomic) IBOutlet UIButton *nameButton;

@end

@implementation HGProfileVC {
    OSSClient * client;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"个人资料";
    
    _headImage.layer.cornerRadius =  self.headImage.width/2;
    _headImage.layer.masksToBounds = YES;
    
    //设置点击手势
    _editView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(modifyPassW:)];
    [_editView addGestureRecognizer:tap];
    
    self.view.backgroundColor = kColorWithFloat(0xEEEEEE);
    self.phoneNum.text = [NSString numberSuitScanf:kQQUserInfoManger.mobile];
    
    [self ossCofig];
    
    _headImage.imageView.contentMode = UIViewContentModeScaleAspectFill;
    [[SDWebImageManager sharedManager] downloadImageWithURL:kPhotoURL(kQQUserInfoManger.avatarUrl) options:SDWebImageProgressiveDownload progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        [_headImage setImage:image forState:(UIControlStateNormal)];
    }];
    
    _nameButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [_nameButton setTitle:kQQUserInfoManger.nickName forState:(UIControlStateNormal)];
}


//oss配置项
- (void)ossCofig {
    
    NSString *endpoint = @"oss-cn-shenzhen.aliyuncs.com";
    //直接访问鉴权服务器（推荐，token过期后可以自动更新）
    id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:@"LTAI5TyZJhGvjivO" secretKeyId:@"hsOlJ8pLxjm2sBvWVdE7q3ebxosHlM" securityToken:@""];
    client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
    OSSClientConfiguration * conf = [OSSClientConfiguration new];
    conf.maxRetryCount = 3; // 网络请求遇到异常失败后的重试次数
    conf.timeoutIntervalForRequest = 30; // 网络请求的超时时间
    conf.timeoutIntervalForResource = 24 * 60 * 60; // 允许资源传输的最长时间
    client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential clientConfiguration:conf];
}



- (IBAction)loginOf:(id)sender {
    
    [LEEAlert alert].config.LeeContent(@"是否退出登录").LeeAddAction(^(LEEAction *action) {
        [action setTitle:@"取消"];//60    70    118
        [action setTitleColor:kColorWithRGB(60, 70, 118)];
    }).LeeAddAction(^(LEEAction *action) {
        [action setTitle:@"确定"];
        [action setTitleColor:[UIColor whiteColor]];
        action.backgroundColor = kColorWithRGB(60, 70, 118);
        action.clickBlock = ^{
            [QQUserInfo logout];
            [[XNProgressHUD shared] showSuccessWithTitle:@"退出成功"];
            QQNavigationController *nav = [[QQNavigationController alloc] initWithRootViewController:[[QQLoginViewController alloc] init]];
            self.view.window.rootViewController = nav;
        };
    }).LeeShadowOpacity(3).LeeCornerRadius(5).LeeShadowOpacity(0.4).LeeShow();
}



- (void)modifyPassW:(UITapGestureRecognizer *)sender {
    QQForgetPassWViewController* vc = [[QQForgetPassWViewController alloc]init];
    vc.type = 1;
    [self.navigationController pushViewController:vc animated:YES];
}

//修改名字
- (IBAction)editName:(UIButton *)sender {
    
    __block UITextField *tf = nil;
    [LEEAlert alert].config.LeeAddTextField(^(UITextField *textField) {
        textField.placeholder = @"请输入昵称";
        textField.textAlignment = NSTextAlignmentCenter;
        textField.borderStyle = UITextBorderStyleNone;
        tf = textField;
    }).LeeAddAction(^(LEEAction *action) {
        [action setTitle:@"取消"];
        [action setTitleColor:kColorWithRGB(60, 70, 118)];
    }).LeeAddAction(^(LEEAction *action) {
        [action setTitle:@"确定"];
        [action setTitleColor:[UIColor whiteColor]];
        action.backgroundColor = kColorWithRGB(60, 70, 118);
        action.clickBlock = ^{
            if (tf.text.length == 0) return;
            [[LMJRequestManager sharedManager] POST:KBaseURL(@"user/nickname") parameters:@{@"nickName" : tf.text} completion:^(LMJBaseResponse *response) {
                if ([response.responseObject[@"status"] integerValue] == 1) {
                    [[XNProgressHUD shared] showSuccessWithTitle:response.responseModel.message];
                    [_nameButton setTitle:tf.text forState:(UIControlStateNormal)];
                }
            }];
            
        };
    }).LeeShadowOpacity(3).LeeCornerRadius(5).LeeShadowOpacity(0.4).LeeShow();
    
}

- (IBAction)changeImageClick:(id)sender {
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                   message:@"选取一张照片作为您的头像" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction* camerAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        [[XZCustomCamer shareCustom] pushPhotoAlbumcholoes:(XZCustomCamerTypeCamer) setPhotoBlock:^(UIImage *image) {
            [self uploadImageIocn:image isScus:^(NSString *image_url) {
                [self upLoadImageData:image_url isScus:^(BOOL isScu) {
                    if (isScu != NO) {
                        [self.headImage setImage:image forState:UIControlStateNormal];
                    }
                }];
            }];
        }];
    }];
    
    UIAlertAction* photoAction = [UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
        [[XZCustomCamer shareCustom] pushPhotoAlbumcholoes:(XZCustomCamerTypePhoto) setPhotoBlock:^(UIImage *image) {
            [self uploadImageIocn:image isScus:^(NSString *image_url) {
                [self upLoadImageData:image_url isScus:^(BOOL isScu) {
                    if (isScu != NO) {
                        [self.headImage setImage:image forState:UIControlStateNormal];
                    }
                }];
            }];
        }];
    }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    [alert addAction:camerAction];
    [alert addAction:photoAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)upLoadImageData:(NSString *)imageFilePath isScus:(void(^)(BOOL isScu))requestisScu {
    NSDictionary *paramters = @{
                                @"avatarUrl" : kisStrNiL(imageFilePath),
                                @"userId" : [NSNumber numberWithInteger:[kQQUserInfoManger.userId integerValue]]
                                };
    
    [[LMJRequestManager sharedManager] POST:KBaseURL(@"user/change/face") parameters:paramters completion:^(LMJBaseResponse *response) {
        if ([response.responseObject[@"status"] integerValue] == 1) {
            kQQUserInfoManger.avatarUrl = response.responseModel.data;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[XNProgressHUD shared] showSuccessWithTitle:response.responseModel.message];
            });
        } else {
            [[XNProgressHUD shared] showErrorWithTitle:response.responseModel.message];
        }
        if (requestisScu) {
            requestisScu([response.responseObject[@"status"] integerValue] == 1 ? YES : NO);
        }
        
    }];
    
}

- (void)uploadImageIocn:(UIImage *)image isScus:(void(^)(NSString *image_url))requestisScu {
    [[XNProgressHUD shared] showLoadingWithTitle:@"上传中" maskType:(XNProgressHUDMaskTypeBlack)];
    NSData *data = [Utility compressOriginalImage:image toMaxDataSizeKBytes:800];
    NSString * objectKey = kOSSBucketKey;
    NSString *filePath = [NSString stringWithFormat:@"head/%@%@.png",kQQUserInfoManger.personalityName,kQQUserInfoManger.mobile];
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    put.bucketName = objectKey;
    put.objectKey = filePath;
    put.uploadingData = data; // 直接上传NSData
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    OSSTask * putTask = [client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            NSLog(@"upload object success!");
            if (requestisScu) {
                requestisScu(filePath);
            }
        } else {
            NSLog(@"upload object failed, error: %@" , task.error);
        }
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [[XNProgressHUD shared] dismiss];
        }];
        return nil;
    }];
}


@end
